// Copyright Copyright 2009 Vladimir Solomenchuk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
dojo.provide("judo.events");
// simulateEvent
// http://blog.pothoven.net/2007/08/synthesizing-events-in-javascript.html
// simulate a user action
//
judo.events={
	simulate:function(eventType, targetElement) {
	    var event;
	    //targetElement = $(targetElement);

	    if (targetElement) {
	     // check for IE
	     if (window.ActiveXObject) {
	         event = document.createEventObject();
	         var res=targetElement.fireEvent("on"+eventType,event);
	         //simulate main event, if possible
	         if (res) {
	        	 if (dojo.isIE) {
	        		 // IE 6: typeof form.submit == 'object'
	        		 var t = typeof targetElement[eventType];
		        	 if (t == 'object' || t == 'function')
		        	 	targetElement[eventType](event);
	        	 } else {
	        		 if (typeof targetElement[eventType] == 'function')
		        	 	targetElement[eventType](event);
	        	 }
	         }	         
	         return res;
	     } else {
	         switch (eventType) {
	             case "abort":
	             case "blur":
	             case "change":
	             case "error":
	             case "focus":
	             case "load":
	             case "reset":
	             case "resize":
	             case "scroll":
	             case "select":
	             case "submit":
	             case "unload":
	                 event = document.createEvent("HTMLEvents");
	                 event.initEvent(eventType, "true", "true");
	                 break;
	             case "click":
	             case "mousedown":
	             case "mousemove":
	             case "mouseout":
	             case "mouseover":
	             case "mouseup":
	                 event = document.createEvent("MouseEvents");
	                 event.initMouseEvent(eventType, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	                 break;
	             default:
	            	 throw new Error("judo.events: invalid event: "+eventType);
	         }
	         var res=targetElement.dispatchEvent(event);
	         if (dojo.isSafari)
	        	 targetElement[eventType](event);
	         return res;
	     }
	    }
	}
};